#include "PWM.h"
int16_t PWM_A_CMP = 0;
int16_t PWM_B_CMP = 0;
int16_t now_cmp = 1;






void PWMA_setcmp(int16_t cmp)
{
    // 设置PWM_A的捕获比较值
    if (cmp >= 0)
    {
        // 正转: AIN1高，AIN2低
        DL_GPIO_setPins(ABIN_PORT, ABIN_AIN1_PIN);
        DL_GPIO_clearPins(ABIN_PORT, ABIN_AIN2_PIN);
        // 修正参数顺序：将cmp作为第三个参数
        DL_TimerG_setCaptureCompareValue(PWM_A_INST, (uint16_t)cmp, GPIO_PWM_A_C0_IDX);
    }
    // else
    // {
    //     // 反转: AIN1低，AIN2高
    //     DL_GPIO_clearPins(ABIN_PORT, ABIN_AIN1_PIN);
    //     DL_GPIO_setPins(ABIN_PORT, ABIN_AIN2_PIN);
    //     // 修正参数顺序：将-cmp作为第三个参数
    //     DL_TimerG_setCaptureCompareValue(PWM_A_INST, (uint16_t)(-cmp), GPIO_PWM_A_C0_IDX);
    // }
}

void PWMB_setcmp(int16_t cmp) // 设置比较寄存器
{
    if (cmp >= 0)
    {

        // 修正参数顺序：将cmp作为第三个参数
        DL_TimerG_setCaptureCompareValue(PWM_B_INST, (uint16_t)cmp, GPIO_PWM_B_C0_IDX);
    }
    // else
    // {
    //     // 反转: BIN1低，BIN2高
        
    //     DL_GPIO_setPins(ABIN_PORT, ABIN_BIN1_PIN);
    //     DL_GPIO_clearPins(ABIN_PORT, ABIN_BIN2_PIN);

    //     // 修正参数顺序：将-cmp作为第三个参数
    //     DL_TimerG_setCaptureCompareValue(PWM_B_INST, 1000-(uint16_t)(-cmp), GPIO_PWM_B_C0_IDX);
    // }
    // uart0_printf("cmp = %d\n",(uint16_t)cmp);
}
void PWMA_setzkb(float zkb)
{
    if (zkb >= 0)// 正转: AIN1高，AIN2低
    {
        if (zkb > 999.0f) zkb = 999.0f;
        uint16_t cmp = 1000 - (uint16_t)zkb;
        DL_GPIO_clearPins(ABIN_PORT, ABIN_AIN1_PIN);
        DL_GPIO_setPins(ABIN_PORT, ABIN_AIN2_PIN);
        DL_TimerG_setCaptureCompareValue(PWM_A_INST, cmp, GPIO_PWM_A_C0_IDX);
    }
    else
    {
        if (zkb < -999.0f) zkb = -999.0f;
        uint16_t cmp = 1000 - (uint16_t)(-zkb);
        
        DL_GPIO_clearPins(ABIN_PORT, ABIN_AIN1_PIN);
        DL_GPIO_clearPins(ABIN_PORT, ABIN_AIN2_PIN); 
        DL_TimerG_setCaptureCompareValue(PWM_A_INST, cmp, GPIO_PWM_A_C0_IDX);
    }
}
void PWMB_setzkb(float zkb) //取值为0~999 越大转动速度越快
{
    if (zkb >= 0)// 正转: BIN1低，BIN2高
    {
        DL_GPIO_clearPins(ABIN_PORT, ABIN_BIN2_PIN);
        DL_GPIO_setPins(ABIN_PORT, ABIN_BIN1_PIN);  
        if (zkb > 999.0f) zkb = 999.0f;
        uint16_t cmp = 1000 - (uint16_t)zkb;
         
        DL_TimerG_setCaptureCompareValue(PWM_B_INST, cmp, GPIO_PWM_B_C0_IDX);
    }
    else 
    {
        if (zkb < -999.0f) zkb = -999.0f;
        uint16_t cmp = 1000 - (uint16_t)(-zkb);
        
        DL_GPIO_clearPins(ABIN_PORT, ABIN_BIN1_PIN);
        DL_GPIO_setPins(ABIN_PORT, ABIN_BIN2_PIN); 
        DL_TimerG_setCaptureCompareValue(PWM_B_INST, cmp, GPIO_PWM_B_C0_IDX);
    }
    
    
}


void PWM_proc(void)
{
    now_cmp ++ ;
    if(now_cmp > 1000)
    {
        now_cmp = 0;
    }
    PWMA_setcmp(now_cmp);
    PWMB_setcmp(now_cmp);
}